﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web;
using System.Linq;
using System.Web.UI;
using WinnerCMS.BLL;
using System.Management;
using WinnerCMS.Common;
using Microsoft.VisualBasic.Devices;
using WinnerCMS.Model;
using WinnerCMS.Model.Attribute;

#endregion

namespace WinnerCMS.WebUI.Admin
{
    /// <summary>
    ///     Main 的摘要说明。
    /// </summary>
    [Access]
    public partial class Main : Page
    {
        protected string strUpDate = "";
        private readonly ComputerInfo _computerinf = new ComputerInfo();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(IsPostBack))
            {
                if (Request["Action"] == null)
                {
                    this.lblVersion.Text = "WinnerCMS  " + SystemInfo.AssemblyVersion;

                    this.lblDataType.Text = "SQLServer 数据库";
                }
            }
        }


        private void GetRunningInfo(HtmlTextWriter writer)
        {
            #region 数据准备

            Func<string> aspnetn = () =>
            {
                try
                {
                    return (Process.GetCurrentProcess().WorkingSet64/1048576).ToString("N2") + " MB";
                }
                catch
                {
                    return "系统拒绝提供。";
                }
            };
            Func<string> cpuUsage = () =>
            {
                try
                {
                    var pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    pcCpuLoad.NextValue();
                    Thread.Sleep(250);
                    return pcCpuLoad.NextValue().ToString("0.00%");
                }
                catch
                {
                    return "权限不足";
                }
            };

            Func<string> getMaxThreads = () =>
            {
                int maxThreadNum, portThreadNum;
                ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
                return maxThreadNum.ToString();
            };

            #endregion

            var json = new
            {
                lblaspnetn = aspnetn.Invoke(),
                lblaspnetcpu = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds.ToString("N0") + " 秒",
                lblserverstart = (Environment.TickCount/3600000).ToString("N2"),
                lblprstart = Process.GetCurrentProcess().StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                lblCpuUsage = cpuUsage.Invoke(),
                lblGetMaxThreads = getMaxThreads.Invoke(),
                lblProcessThread = Process.GetCurrentProcess().Threads.Count,
                lbldwMemoryLoad =
                    (this._computerinf.AvailablePhysicalMemory/(double) this._computerinf.TotalPhysicalMemory).ToString(
                        "P2"),
                lbldwAvailPhys = FileSize(this._computerinf.AvailablePhysicalMemory),
                lbldwAvailPageFile = FileSize(this._computerinf.TotalPhysicalMemory),
                lblservers = Session.Contents.Count,
                lblservera = Application.Contents.Count,
                lblCache = HttpRuntime.Cache.Count,
                lblCacheMax = FileSize(HttpRuntime.Cache.EffectivePrivateBytesLimit)
            };


            Response.Write(json.ToJson());
        }


        private static string FileSize(double fileSize)
        {
            if (fileSize < 1024)
            {
                return fileSize + " B";
            }
            if ((fileSize < 1024*1024))
            {
                return Math.Round((fileSize/1024), 2) + " KB";
            }
            return Math.Round(fileSize/(1024*1024), 2) + " MB";
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (Request["Action"] == "GetRunningInfo")
            {
                Context.Response.Expires = 0;
                Context.Response.CacheControl = "no-cache";
                Context.Response.ContentType = "text/plain";

                GetRunningInfo(writer);
            }
            else
            {
                base.Render(writer);
            }
        }
    }
}